package model

import (
	"fmt"
	"github.com/olivere/elastic/v7"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/schema"
)

type MysqlConf struct {
	Username string
	Password string
	Host     string
	Port     int
	Database string
}
type EsConf struct {
	Host string
	Port int
}

var (
	mysqlConfig MysqlConf
	esConfig    EsConf
	DB          *gorm.DB
	EsClient    *elastic.Client
)

const ES_INDEX = "month"

func ConfigInit() {
	mysqlConfig = MysqlConf{
		Username: "root",
		Password: "root",
		Host:     "127.0.0.1",
		Port:     3306,
		Database: "zg6",
	}
	esConfig = EsConf{
		Host: "127.0.0.1",
		Port: 9277,
	}
}
func MysqlInit() {
	var (
		err error
		dsn = fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8&parseTime=True&loc=Local",
			mysqlConfig.Username, mysqlConfig.Password, mysqlConfig.Host, mysqlConfig.Port, mysqlConfig.Database,
		)
	)
	DB, err = gorm.Open(mysql.New(mysql.Config{
		DSN:                       dsn,   // DSN data source name
		DefaultStringSize:         256,   // string 类型字段的默认长度
		DisableDatetimePrecision:  true,  // 禁用 datetime 精度，MySQL 5.6 之前的数据库不支持
		DontSupportRenameIndex:    true,  // 重命名索引时采用删除并新建的方式，MySQL 5.7 之前的数据库和 MariaDB 不支持重命名索引
		DontSupportRenameColumn:   true,  // 用 `change` 重命名列，MySQL 8 之前的数据库和 MariaDB 不支持重命名列
		SkipInitializeWithVersion: false, // 根据当前 MySQL 版本自动配置
	}), &gorm.Config{
		NamingStrategy: schema.NamingStrategy{
			SingularTable: false,
			TablePrefix:   "month_",
		},
	})
	if err != nil {
		panic(err)
	}
	err = DB.AutoMigrate(&OrderDetail{})
	err = DB.AutoMigrate(&Order{})
	if err != nil {
		panic(err)
	}
}
func EsInit() {
	var (
		err error
		dsn = fmt.Sprintf("http://%s:%d", esConfig.Host, esConfig.Port)
	)
	EsClient, err = elastic.NewClient(elastic.SetURL(dsn), elastic.SetSniff(false))
	if err != nil {
		panic(err)
	}
}
